package cn.pugle.json.jackson;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.junit.Test;

import java.io.IOException;

/**
 * 反序列化.
 * 另外想自定义post deserialize行为, 见 https://stackoverflow.com/a/18405958/5142886
 *
 * @author tzp
 * @since 2018/9/20
 */
public class TestDeserialization {


    @Test
    public void test() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule module = new SimpleModule();
        module.addDeserializer(Dog.class, new DogDeserializer(Dog.class));
        mapper.registerModule(module);


        String json = "{\"age\":1,\"the_name\":\"doggie\"}";
        Dog dog = mapper.readValue(json, Dog.class);
        System.out.println(dog);

    }

    public static class DogDeserializer extends StdDeserializer<Dog> {

        protected DogDeserializer(Class<?> vc) {
            super(vc);
        }

        @Override
        public Dog deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
            return new Dog();
        }
    }
}
